package com.lee.dutylower.view.setting;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;


import com.lee.dutylower.MyApplication;
import com.lee.dutylower.R;
import com.lee.dutylower.db.greenEntity.Sentry;
import com.lee.dutylower.db.greendao.SentryDao;
import com.lee.dutylower.utils.ToastUtils;
import com.lee.dutylower.view.BaseFragment;
import com.lee.dutylower.view.detail.SentryDetailFragment;

import java.util.List;

/**
 * Created by lijie on 2017/4/28.
 */

public class SentrySettingFragment extends BaseFragment {
    private TextView tvSettingName;
    private TextView tvSettingListName;
    private ListView lvData;
    private MyAdapter myAdapter;
    private int lastPosition = -1;
    //private LinearLayoutManager layoutManager;
    private SentryDao sentryDao;

    private Sentry currentSentry;

    public Button btnAdd;
    public Button btnSave;
    public Button btnEdit;
    private List<Sentry> values;
    private SentryDetailFragment detailFragment;

    public SentrySettingFragment() {
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        lastPosition = -1;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        sentryDao = MyApplication.getApplication().getDaoSession().getSentryDao();
        View v = View.inflate(getActivity(), R.layout.fragment_setting,null);
        tvSettingName = (TextView) v.findViewById(R.id.tv_setting_name);
        tvSettingListName = (TextView) v.findViewById(R.id.tv_setting_list_name);
        lvData = (ListView) v.findViewById(R.id.lv_setting_db);

        tvSettingName.setText("哨位设置");
        tvSettingListName.setText("全部哨位");
        btnAdd = (Button) v.findViewById(R.id.btn_add_data);
        btnSave = (Button) v.findViewById(R.id.btn_data_save);
        btnEdit = (Button) v.findViewById(R.id.btn_data_edit);

        values = sentryDao.queryBuilder().build().list();
        myAdapter = new MyAdapter();
        lvData.setAdapter(myAdapter);

        lvData.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                btnSave.setVisibility(View.INVISIBLE);
                btnEdit.setEnabled(true);

                lastPosition = position;
                TextView tv = (TextView) view.findViewById(R.id.tv_lv_data);
                tv.setTextSize(20);
                tv.setBackgroundColor(0xFFA36F59);
                myAdapter.notifyDataSetChanged();

                MyAdapter.ViewHolder holder = (MyAdapter.ViewHolder) view.getTag();
                String squadid = holder.ID.getText().toString();
                Sentry sentry =sentryDao.queryBuilder().where(SentryDao.Properties.Sentry_id.eq(Long.parseLong(squadid))).build().unique();
                currentSentry = sentry;
                detailFragment = new SentryDetailFragment();
                addFragment(detailFragment,sentry,"Sentry");

                btnEdit.setVisibility(View.VISIBLE);
            }
        });

        lvData.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                MyAdapter.ViewHolder holder = (MyAdapter.ViewHolder) view.getTag();
                final String sid = holder.ID.getText().toString();
                AlertDialog alert ;
                TextView tv = (TextView) view.findViewById(R.id.tv_lv_data);
                tv.setTextSize(20);
                tv.setBackgroundColor(0xFFA36F59);
                myAdapter.notifyDataSetChanged();
                alert = new AlertDialog.Builder(getActivity())
                        .setTitle("删除")
                        .setMessage("确认删除 数据：" + tv.getText() + "?")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                sentryDao.deleteByKey(Long.parseLong(sid));
                                values = sentryDao.queryBuilder().build().list();
                                myAdapter.notifyDataSetChanged();
                            }
                        })
                        .setNegativeButton("取消", null)
                        .create();
                alert.show();
                return true;
            }
        });


        //新增数据按钮
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lastPosition = -1;
                btnEdit.setEnabled(false);
                btnSave.setVisibility(View.VISIBLE);
                btnSave.setEnabled(true);
                detailFragment = new SentryDetailFragment();
                addEmptyFragment(detailFragment);
                myAdapter.notifyDataSetChanged();
            }
        });
        //保存数据
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = detailFragment.etName.getText().toString();
                int type = detailFragment.type;
                name = name.trim();
                if("".equals(name)){
                    ToastUtils.showShort(getActivity(),"名称不能为空");
                    return;
                }
                if (type == -1){
                    ToastUtils.showShort(getActivity(),"请选择哨位类型");
                    return;
                }
                if (detailFragment.isAdd){
                    Sentry nSentry = new Sentry();
                    nSentry.setSentry_name(name);
                    nSentry.setSentry_type(type);
                    sentryDao.insert(nSentry);
                    values = sentryDao.queryBuilder().build().list();
                    myAdapter.notifyDataSetChanged();
                    ToastUtils.showShort(getActivity(),"插入成功");
                    detailFragment = new SentryDetailFragment();
                    addEmptyFragment(detailFragment);
                }else {
                    currentSentry.setSentry_name(name);
                    currentSentry.setSentry_type(type);
                    sentryDao.update(currentSentry);
                    values = sentryDao.queryBuilder().build().list();
                    myAdapter.notifyDataSetChanged();
                    ToastUtils.showShort(getActivity(),"修改成功");
                    Sentry squadDB = sentryDao.queryBuilder().where(SentryDao.Properties.Sentry_id.eq(currentSentry.getSentry_id())).build().unique();
                    currentSentry = squadDB;
                    detailFragment = new SentryDetailFragment();
                    addFragment(detailFragment,squadDB,"Sentry");
                }

                btnSave.setVisibility(View.INVISIBLE);
                btnEdit.setEnabled(true);
            }
        });

        btnEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnEdit.setEnabled(false);

                detailFragment = new SentryDetailFragment();
                addEditFragment(detailFragment,currentSentry,"Sentry");

                btnSave.setVisibility(View.VISIBLE);
            }
        });


        return v;
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    class MyAdapter extends BaseAdapter {

        public MyAdapter() {

        }

        @Override
        public int getCount() {
            return values.size();
        }

        @Override
        public Object getItem(int position) {
            return values.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            Sentry sentry = values.get(position);
            if(convertView == null){
                holder = new ViewHolder();
                convertView = View.inflate(getActivity(),R.layout.listview_item,null);
                holder.tv = (TextView) convertView.findViewById(R.id.tv_lv_data);
                holder.ID = (TextView) convertView.findViewById(R.id.tv_lv_id);
                convertView.setTag(holder);
            }else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.tv.setText(sentry.getSentry_name());
            holder.ID.setText(sentry.getSentry_id()+"");

            if(lastPosition != position){
                holder.tv.setTextSize(16);
                holder.tv.setBackgroundColor(0xFFB38672);
            }else {
                holder.tv.setTextSize(20);
                holder.tv.setBackgroundColor(0xFFA36F59);
            }

            return convertView;
        }

        class ViewHolder{
            TextView tv;
            TextView ID;
        }
    }
}
